/*
 * @author Ihsan Al-Hamoud
 * @Web www.al-hamoud.com
 * @Web www.patternsexpert.com
 * @version 1.0
 * If you need a completed Blogger with GWT
 * as Client side. Please email me on
 * ihsan.alhamoud@gmail.com
 * I will be very happy to help.
 */
package com.patternsexpert.blog.server;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.patternsexpert.blog.client.entities.Article;

@SuppressWarnings("serial")
public class ArticleAction extends HttpServlet{
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		if(isAuthorized(user.getEmail())){
			
			cookies = request.getCookies();
			this.initCookies();
			
			String msg = "";
			
			String title= null;
			String des = null;
			String tex = null;
			
			String action = null;

			////////////////////// JSON ////////////////////////////////////	
			String json = request.getParameter("json");
			
			/* For back message to the client as JSON format */
			JSONObject jsonMSG;
			
			JSONObject data;
			try {
				data = new JSONObject(json);

				sid		= data.getString("sid");
				ip		= data.getString("ip");
				protocol= data.getString("protocol");
				port	= data.getString("port");
				scheme	= data.getString("scheme");
				
				action	= data.getString("action");
				
				title	= data.getString("title");
				tex		= data.getString("text");
				des		= data.getString("des");

			} catch (JSONException e) {
				e.printStackTrace();
			}// end of catch
	//////////////////////////////// JSON //////////////////////////////////////

			String email = user != null ? user.getEmail(): "Guest";
			
			/** initialise ArticleServices with ArticleModel reference  **/
			ArticleServices event = new ArticleModel(title, email);
			
			/* To implements an create or upload action */
			if(action.equalsIgnoreCase("create")){
				
				/*the checkArticle returns null if a new article has been created */
				Article r = event.checkArticle();
				if(r != null){
					
					try{
						jsonMSG = new JSONObject();
						
						jsonMSG.put("msg", msg);
						jsonMSG.put("des", r.getDescription());
						jsonMSG.put("text", r.getText());
						
						msg = jsonMSG.toString();
					}catch (JSONException ex) {
						System.out.println("JSON Error " + ex.toString());
			        }// end catch
					
				}/* End of if for an existed article */
				else{
					
					/* Giving a message to client the article has been created */
					try{
						jsonMSG = new JSONObject();
						jsonMSG.put("msg", "Article has been created");
						msg = jsonMSG.toString();
					}catch (JSONException ex){
						System.out.println("JSON Error " + ex.toString());
			        }// end of catch
					/* End of giving a message to client the article has been created */

				}/* End of else for new creation */
				
			}/* End of if for creation or uploading an existed article */
			
			/* To implements an update action */
			else if(action.equalsIgnoreCase("update")){
				event.updateArticle(title, des, tex);
				Article r = event.retrieveArticle();
				if(r != null){
					
					/* Return the id of the updated article to the client */
					try{
						jsonMSG = new JSONObject();
						//jsonMSG.put("msg", "");
						jsonMSG.put("msg", r.getId().toString());
						msg = jsonMSG.toString();
						//msg = r.getId().toString();
					}catch (JSONException ex){
						System.out.println("JSON Error " + ex.toString());
			        }// end of catch
					/* End of return the id of the updated article to the client */
				}/* End of if */
				
			}/* End of else if for updating an article */
			
			/* To implements publish action */
			else if(action.equalsIgnoreCase("publish")){
				event.publishArticle();
				Article r = event.retrieveArticle();
				if(r != null){
					
					/* Return the id of the published article to the client */
					try{
						jsonMSG = new JSONObject();
						jsonMSG.put("msg", r.getId().toString());
						//jsonMSG.put("aid", r.getId().toString());
						msg = jsonMSG.toString();
						//msg = r.getId().toString();
					}catch (JSONException ex){
						System.out.println("JSON Error " + ex.toString());
			        }// end of catch
					/* End of return the id of the published article to the client */
				}/* End of if for non null article */
				
			}/* End of else if for publishing an article */
			
			/* exit from the system */
			else{
				System.exit(1);
				
			}/* End of else for Error action for any other reason */
			
			PrintWriter writer = response.getWriter();
			writer.println(msg);
			writer.close();
						
		}// end of Authorised action 
		
	}// End of doGet
	
	//////////////////////////////// Temp verification //////////
	
	private static final String [] EV = {
		"ihsan.alhamoud@gmail.com",
		"ihsanho@gmail.com",
		"khalil.i.khalil@gmail.com"
		};	
	
	private static boolean isAuthorized(String email){
		for(String check: EV){
			if(check.equals(email)){
				return true;
			}
		}
		return false;
	}// end of isAutherized function 
	///////////// end of Temp Authorized //////////////////
	
///////////////Cookies Verification /////////////////	
	@SuppressWarnings("unused")
	private String sid;
	@SuppressWarnings("unused")
	private String ip;
	@SuppressWarnings("unused")
	private String protocol;
	@SuppressWarnings("unused")
	private String port;
	@SuppressWarnings("unused")
	private String scheme;

	private Cookie[] cookies;
	
	private void initCookies(){
		
		for(Cookie cc : cookies){
			if (cc.getName().equals("sid")){
				sid = cc.getValue();
			}
			if(cc.getName().equals("ip")){
				ip = cc.getValue();
			}
			if(cc.getName().equals("scheme")){
				scheme = cc.getValue();
			}
			if(cc.getName().equals("port")){
				port = cc.getValue();
			}
			if(cc.getName().equals("protocol")){
				protocol = cc.getValue();
			}// end of if stmt. for initial cProtocol 
			
		}// end of loop for parsing cookies
		
	}// end of checkSessionUser
////////////////End of Cookies Verification //////////
}/* End of ArticleAction */